package cc.yiueil.filter;

import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Locale;

@Component
public class CaptchaFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        String requestURI = request.getRequestURI();
        if (requestURI.contains("/customLogin")) {
            String c = request.getParameter("captcha");
            if (!StringUtils.hasText(c)) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
            String captcha = request.getSession().getAttribute("code").toString();
            if (!c.toLowerCase(Locale.ROOT).equals(captcha.toLowerCase(Locale.ROOT))) {
                response.sendError(HttpServletResponse.SC_BAD_REQUEST);
                return;
            }
        }
        filterChain.doFilter(request, response);
    }
}
